<?php
namespace Asset\Controller;
use Common\Controller\AdminbaseController;
use Library\Wx;
class AnalysisController extends AdminbaseController {
	protected $region_model,
			$real_users_model,
			$analysis_gather_model,
			$analysis_day_model,
			$analysis_logs_model,
			$analysis_urls_model,
			$analysis_activity_model,
			$analysis_materials_model,
			$analysis_equipment_model,
			$analysis_winning_model,
			$wxpayorder_model,
			$analysis_users_model;
	function _initialize() {
		parent::_initialize();
		$this->region_model = D("Region");
        $this->real_users_model = M("RealUsers");
		$this->analysis_gather_model= D("AnalysisGather");
		$this->analysis_day_model= D("AnalysisDay");
		$this->analysis_logs_model= D("AnalysisLogs");
		$this->analysis_urls_model= D("AnalysisUrls");
		$this->analysis_activity_model= D("AnalysisActivity");
		$this->analysis_materials_model= D("AnalysisMaterials");
		$this->analysis_equipment_model= D("AnalysisEquipment");
		$this->analysis_winning_model= D("AnalysisWinning");
        $this->wxpayorder_model = M("WxPayOrder");
		$this->analysis_users_model= D("AnalysisUsers");
        $this->backup_path = '/data/';
	}
    private function arraytypes() {
		$arraytypes =array(
	        array(
	            array('id' => '0', 'name'=>'请选择'),
	            array('id' => '1', 'name'=>'设备ID'),
	            array('id' => '2', 'name'=>'店铺名称'),
	            array('id' => '3', 'name'=>'店铺地址'),
	            array('id' => '4', 'name'=>'合伙人'),
	            array('id' => '5', 'name'=>'合伙人电话'),
	            array('id' => '6', 'name'=>'店铺地区'),
	        ),
	        array(
				array('id'=>'0','name'=>'请选择'),
				array('id'=>'100','name'=>'电影院'),
				array('id'=>'105','name'=>'私人影吧'),
				array('id'=>'110','name'=>'奶茶/水吧'),
				array('id'=>'120','name'=>'商超'),
				array('id'=>'125','name'=>'KTV'),
				array('id'=>'130','name'=>'便利店'),
				array('id'=>'135','name'=>'烘培蛋糕店'),
				array('id'=>'140','name'=>'西餐厅/中餐厅'),
				array('id'=>'150','name'=>'咖啡/甜品店'),
				array('id'=>'160','name'=>'酒吧/夜店'),
				array('id'=>'170','name'=>'小吃店/零食店'),
				array('id'=>'180','name'=>'网咖/网吧'),
				array('id'=>'190','name'=>'主题公园/景区'),
				array('id'=>'200','name'=>'副食品店'),
				array('id'=>'500','name'=>'其他'),
			),
        	array(
	            array('id' => '1', 'name'=>'成功'),
	            array('id' => '2', 'name'=>'失败'),
        	),
        	array(
	            array('id' => '1', 'name'=>'普通红包'),
	            array('id' => '2', 'name'=>'提现红包'),
        	),
	        array(
				array('id'=>'0','name'=>'请选择'),
				array('id'=>'1','name'=>'统计日期'),
				array('id'=>'2','name'=>'创建日期'),
				array('id'=>'3','name'=>'登录日期')
			)
		);
		return $arraytypes;
	}
	//汇总报表
    function index() {
		$userid = get_current_admin_id();
		$roleid =  get_current_adminrole_id();
		if (!$userId) {
			if ($roleid >= 20) {
				$this->redirect('materials');
			}
		}
		if(I('param.')){
            if(I('param.start_time')){
                    $search[] = array('date(datetime)'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('date(datetime)'=>array('elt',I('param.end_time')));
            }
            if(I('param.keyword')){
                    $search[] = array('pageid'=>I('param.keyword'));
            }
			$_GET['keyword']=I('param.keyword');
            $_GET['start_time'] = I('param.start_time');
            $_GET['end_time'] = I('param.end_time');
		}
		$count=$this->analysis_gather_model
		->where($search)
		->count();
		$page = $this->page($count, 50);
		$analysis = $this->analysis_gather_model
		->where($search)
		->limit($page->firstRow . ',' . $page->listRows)
		->order("id DESC")
		->select();
		$subQuery = $this->analysis_gather_model
		->order("id DESC")
		->buildSql();
		$pageids = $this->analysis_gather_model
		->table($subQuery.' a')
		->group("pageid")
		->select();
		$this->assign("analysis", $analysis);
		$this->assign("page", $page->show('Admin'));
		$this->assign("count",$count);
		$this->assign("pageids",$pageids);
		$this->display();
    }
	//单日
    function day(){
		if(I('param.')){
            if(I('param.start_time')){
                    $search[] = array('date(datetime)'=>array('egt',I('param.start_time')));
                    $dsearch[] = array('date(time)'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('date(datetime)'=>array('elt',I('param.end_time')));
                    $dsearch[] = array('date(time)'=>array('elt',I('param.end_time')));
            }
            if(I('param.keyword')){
                    $search[] = array('pageid'=>I('param.keyword'));
            }
			$_GET['keyword']=I('param.keyword');
            $_GET['start_time'] = I('param.start_time');
            $_GET['end_time'] = I('param.end_time');
		}
		$count=$this->analysis_day_model
		->where($search)
		->count();
		$page = $this->page($count, 50);
		$analysis = $this->analysis_day_model
		->where($search)
		->limit($page->firstRow . ',' . $page->listRows)
		->order("id DESC")
		->select();
		if(empty($search)){
			$search[] = array('date(datetime)'=>array('eq',date('Y-m-d',strtotime('-1 day'))));
			$dsearch[] = array('date(time)'=>array('eq',date('Y-m-d',strtotime('-1 day'))));
		}
		$tsum = $this->analysis_day_model
		->field("sum(`shake_uv`) as `shake_uv`,
				sum(`shake_pv`) as `shake_pv`,
				sum(`click_uv`) as `click_uv`,
				sum(`click_pv`) as `click_pv`,
				sum(`count`) as `count`,
				sum(`open`) as `open`,
				sum(`close`) as `close`,
				sum(`partake`) as `partake`,
				sum(`winning`) as `winning`,
				sum(`nowinning`) as `nowinning`,
				sum(`reds`) as `reds`,
				sum(`moneys`) as `moneys`,
				sum(`cards`) as `cards`,
				sum(`reals`) as `reals`")
		->where($search)
		->select();
        $wxpayorder=$this->wxpayorder_model->field("sum(`total_amount`) as `total_amount`")
        ->where($dsearch)
        ->select();

		$tsum[0]['withdraw'] = $wxpayorder[0]['total_amount'];

		$pageids=$this->analysis_day_model
		->group('pageid')
		->order("id DESC")
		->select();
		$this->assign("analysis", $analysis);
		$this->assign("tsum",$tsum);
		$this->assign("page", $page->show('Admin'));
		$this->assign("count",$count);
		$this->assign("pageids",$pageids);
		$this->display();
	}
	//单活动
    function activity(){
		if(I('param.')){
            if(I('param.start_time')){
                    $search[] = array('date(datetime)'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('date(datetime)'=>array('elt',I('param.end_time')));
            }
            if(I('param.keyword')){
                    $search[] = array('event_id'=>I('param.keyword'));
            }
			$_GET['keyword']=I('param.keyword');
            $_GET['start_time'] = I('param.start_time');
            $_GET['end_time'] = I('param.end_time');
		}
		$count=$this->analysis_activity_model
		->where($search)
		->count();
		$page = $this->page($count, 50);
		$analysis = $this->analysis_activity_model
		->where($search)
		->limit($page->firstRow . ',' . $page->listRows)
		->order("id DESC")
		->select();
		if(empty($search)){
			$search[] = array('date(datetime)'=>array('eq',date('Y-m-d',strtotime('-1 day'))));
		}
		$tsum = $this->analysis_activity_model
		->field("sum(`device`) as `device`,
				sum(`enter_uv`) as `enter_uv`,
				sum(`enter_pv`) as `enter_pv`,
				sum(`materials`) as `materials`,
				sum(`winning`) as `winning`,
				sum(`nowinning`) as `nowinning`")
		->where($search)
		->select();
		$eventids=$this->analysis_activity_model
		->group('event_id')
		->order("id DESC")
		->select();
		$this->assign("analysis", $analysis);
		$this->assign("tsum",$tsum);
		$this->assign("page", $page->show('Admin'));
		$this->assign("count",$count);
		$this->assign("eventids",$eventids);
		$this->display();
	}
	//单物料
    function materials(){
		$userid = get_current_admin_id();
		$roleid =  get_current_adminrole_id();
		if (!$userId) {
			if ($roleid >= 20) {
				$search[] = array('userid'=>$userid);
			}
		}
		if(I('param.')){
            if(I('param.start_time')){
                    $search[] = array('date(datetime)'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('date(datetime)'=>array('elt',I('param.end_time')));
            }
            if(I('param.keyword')){
                    $search[] = array('card_id'=>I('param.keyword'));
            }
			$_GET['keyword']=I('param.keyword');
            $_GET['start_time'] = I('param.start_time');
            $_GET['end_time'] = I('param.end_time');
		}
		$count = $this->analysis_materials_model->join('left join yy_card on yy_analysis_materials.card_id = yy_card.id')
			->field('yy_analysis_materials.*, yy_card.userid')
			->where($search)
			->count();
		$page = $this->page($count, 50);
		$analysis = $this->analysis_materials_model->join('left join yy_card on yy_analysis_materials.card_id = yy_card.id')
			->field('yy_analysis_materials.*, yy_card.userid')
			->where($search)
			->limit($page->firstRow . ',' . $page->listRows)
			->order("id DESC")
			->select();
		if(empty($search)){
			$search[] = array('date(datetime)'=>array('eq',date('Y-m-d',strtotime('-1 day'))));
		}
		if (!$userId) {
			if ($roleid < 20) {
				$tsum = $this->analysis_materials_model
					->field("sum(`display_uv`) as `display_uv`,
					sum(`display_pv`) as `display_pv`,
					sum(`winning`) as `winning`,
					sum(`nowinning`) as `nowinning`")
					->where($search)
					->select();
				$search1[] = $search;
				$search1[] = array('card_type'=>array('eq',1));
				$redmoney = $this->analysis_materials_model
					->where($search1)
					->Sum('moneys');
				$search2[] = $search;
				$search2[] = array('card_type'=>array('neq',1));
				$cardmoney = $this->analysis_materials_model
					->where($search2)
					->Sum('moneys');
				$cardids=$this->analysis_materials_model
					->group('card_id')
					->order("id DESC")
					->select();

				$this->assign("tsum",$tsum);
				$this->assign("redmoney",$redmoney);
				$this->assign("cardmoney",$cardmoney);
				$this->assign("card_type", C('CARD_TYPE'));
				$this->assign("page", $page->show('Admin'));
				$this->assign("cardids",$cardids);
			}
		}
		$this->assign("analysis", $analysis);
		$this->assign("count",$count);
		$this->display();
	}
	//单设备
    function equipment(){
		if(I('param.')){
			$keyword =I('param.keyword');
			if(I('param.search') ==1){$search[] = array('devid'=>array('like',"%$keyword%"));}
			if(I('param.search') ==2){$search[] = array('bsname'=>array('like',"%$keyword%"));}
			if(I('param.search') ==3){$search[] = array('bsaddress'=>array('like',"%$keyword%"));}
			if(I('param.search') ==4){$search[] = array('partner'=>array('like',"%$keyword%"));}
			if(I('param.search') ==5){$search[] = array('mobile'=>array('like',"%$keyword%"));}
			if(I('param.search') ==6){
				$sregion = "name like'%$keyword%' or name_en like'%$keyword%'";
				$region = $this->region_model->where("$sregion")->find();
				$search[] =array(array('province_id'=>$region['code']),
								'_logic'=>"OR",
								array('city_id'=>$region['code']),
								'_logic'=>"OR",
								array('district_id'=>$region['code']),
								);
			}
            if(I('param.bstype')){
                $search[] = array('bstype'=>I('param.bstype'));
            }
            if(I('param.start_time')){
                    $search[] = array('date(datetime)'=>array('egt',I('param.start_time')));
                    $dsearch[] = array('date(datetime)'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('date(datetime)'=>array('elt',I('param.end_time')));
                    $dsearch[] = array('date(datetime)'=>array('elt',I('param.end_time')));
            }
            $_GET['stype'] = I('param.stype');
            $_GET['status'] = I('param.status');
			$_GET['search']=I('param.search');
			$_GET['keyword']=I('param.keyword');
            $_GET['start_time'] = I('param.start_time');
            $_GET['end_time'] = I('param.end_time');
		}
		$count=$this->analysis_equipment_model
		->where($search)
		->count();
		$page = $this->page($count, 50);
		$analysis = $this->analysis_equipment_model
		->where($search)
		->limit($page->firstRow . ',' . $page->listRows)
		->order("id DESC")
		->select();
		if($analysis){
			foreach($analysis as$analysi){
				$cord[] =$analysi['province_id'];
				$cord[] =$analysi['city_id'];
				$cord[] =$analysi['district_id'];
			}
			$region = $this->region_model->where(array('code'=>array('in',$cord)))->select();
		}
		$btypes = $this->arraytypes();
		if(empty($search)){
			$search[] = array('date(datetime)'=>array('eq',date('Y-m-d',strtotime('-1 day'))));
		}
		$tsum = $this->analysis_equipment_model
		->field("sum(`activitys`) as `activitys`,
				sum(`click_pv`) as `click_pv`,
				sum(`click_uv`) as `click_uv`,
				sum(`winning`) as `winning`,
				sum(`nowinning`) as `nowinning`,
				sum(`reds`) as `reds`,
				sum(`moneys`) as `moneys`,
				sum(`cards`) as `cards`,
				sum(`reals`) as `reals`")
		->where($search)
		->select();
        $search[] = array('click_uv'=>array('egt',1));
		$tsum[0]['uses'] = $this->analysis_equipment_model->where($search)->count();
        $search[] = array('click_uv'=>array('egt',5));
		$tsum[0]['active'] = $this->analysis_equipment_model->where($search)->count();
		$tsum[0]['people'] = count($this->analysis_urls_model->where($dsearch)->group('openid')->select());
		$tsum[0]['hits'] = $this->analysis_urls_model->where($dsearch)->count();
		$this->assign("analysis", $analysis);
		$this->assign("region", $region);
		$this->assign("btypes", $btypes[1]);
		$this->assign("search", $btypes[0]);
		$this->assign("tsum",$tsum);
		$this->assign("page", $page->show('Admin'));
		$this->assign("count",$count);
		$this->display();
	}
	//单用户
    function users(){
		if(I('param.')){
            if(I('param.keyword')){
                    $search[] = array('openid'=>I('param.keyword'));
            }
            if(I('param.btime')){
	            if(I('param.btime') == 1){
		            if(I('param.start_time')){
		                    $search[] = array('date(datetime)'=>array('egt',I('param.start_time')));
		            }
		            if(I('param.end_time')){
		                    $search[] = array('date(datetime)'=>array('elt',I('param.end_time')));
		            }
	            }
	            if(I('param.btime') == 2){
		            if(I('param.start_time')){
		                    $search[] = array('date(registered)'=>array('egt',I('param.start_time')));
		            }
		            if(I('param.end_time')){
		                    $search[] = array('date(registered)'=>array('elt',I('param.end_time')));
		            }
	            }
	            if(I('param.btime') == 3){
		            if(I('param.start_time')){
		                    $search[] = array('date(enter)'=>array('egt',I('param.start_time')));
		            }
		            if(I('param.end_time')){
		                    $search[] = array('date(enter)'=>array('elt',I('param.end_time')));
		            }
	            }
            }
			$_GET['keyword']=I('param.keyword');
			$_GET['btime']=I('param.btime');
            $_GET['start_time'] = I('param.start_time');
            $_GET['end_time'] = I('param.end_time');
		}
		$count=$this->analysis_users_model
		->where($search)
		->count();
		$page = $this->page($count, 50);
		$analysis = $this->analysis_users_model
		->where($search)
		->limit($page->firstRow . ',' . $page->listRows)
		->order("id DESC")
		->select();
		if(empty($search)){
			$search[] = array('date(datetime)'=>array('eq',date('Y-m-d',strtotime('-1 day'))));
		}
		$tsum = $this->analysis_users_model
		->field("sum(`winning`) as `winning`,
				sum(`reds`) as `reds`,
				sum(`moneys`) as `moneys`,
				sum(`cards`) as `cards`,
				sum(`reals`) as `reals`,
				sum(`shakes`) as `shakes`")
		->where($search)
		->select();
		$tsum[0]['people'] = count($this->analysis_users_model->where($search)->group('openid')->select());

        if(I('param.start_time')){
                $search[] = array('date(registered)'=>array('egt',I('param.start_time')));
        }else{
                $search[] = array('date(registered)'=>array('egt',date('Y-m-d',strtotime('-1 day'))));
        }
        if(I('param.end_time')){
                $search[] = array('date(registered)'=>array('elt',I('param.end_time')));
        }else{
                $search[] = array('date(registered)'=>array('elt',date('Y-m-d',strtotime('-1 day'))));
        }

		$tsum[0]['news'] = count($this->analysis_users_model->where($search)->group('openid')->select());

		$tsum[0]['olds'] = $tsum[0]['people'] - $tsum[0]['news'];
		$btypes = $this->arraytypes();
		$this->assign("btime", $btypes[4]);
		$this->assign("analysis", $analysis);
		$this->assign("tsum",$tsum);
		$this->assign("page", $page->show('Admin'));
		$this->assign("count",$count);
		$this->display();
	}
    function winning(){
		$userid = get_current_admin_id();
		$roleid =  get_current_adminrole_id();
		if (!$userId) {
			if ($roleid >= 20) {
				$search[] = array('userid'=>$userid);
			}
		}
		if(I('param.')){
			$keyword =I('param.keyword');
			if(I('param.search') ==1){$search[] = array('devid'=>array('like',"%$keyword%"));}
			if(I('param.search') ==2){$search[] = array('bsname'=>array('like',"%$keyword%"));}
			if(I('param.search') ==3){$search[] = array('bsaddress'=>array('like',"%$keyword%"));}
			if(I('param.search') ==4){$search[] = array('partner'=>array('like',"%$keyword%"));}
			if(I('param.search') ==5){$search[] = array('mobile'=>array('like',"%$keyword%"));}
			if(I('param.search') ==6){
				$sregion = "name like'%$keyword%' or name_en like'%$keyword%'";
				$region = $this->region_model->where("$sregion")->find();
				$search[] =array(array('province_id'=>$region['code']),
								'_logic'=>"OR",
								array('city_id'=>$region['code']),
								'_logic'=>"OR",
								array('district_id'=>$region['code']),
								);
			}
            if(I('param.bstype')){
                $search[] = array('bstype'=>I('param.bstype'));
            }
            if(I('param.bctype')){
                $search[] = array('ctype'=>I('param.bctype'));
            }
            if(I('param.start_time')){
                    $search[] = array('datetime'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('datetime'=>array('elt',I('param.end_time')));
            }
            $_GET['stype'] = I('param.stype');
            $_GET['status'] = I('param.status');
			$_GET['search']=I('param.search');
			$_GET['keyword']=I('param.keyword');
            $_GET['start_time'] = I('param.start_time');
            $_GET['end_time'] = I('param.end_time');
		}
		$count=$this->analysis_winning_model->join('left join yy_card on yy_analysis_winning.cid = yy_card.id')
			->field('yy_analysis_winning.*, yy_card.userid')
			->where($search)
			->count();
		$page = $this->page($count, 50);
		$analysis = $this->analysis_winning_model->join('left join yy_card on yy_analysis_winning.cid = yy_card.id')
			->field('yy_analysis_winning.*, yy_card.userid')
			->where($search)
			->limit($page->firstRow . ',' . $page->listRows)
			->order("id DESC")
			->select();
		if($analysis){
			foreach($analysis as$analysi){
				$openid[] =$analysi['openid'];
				$cord[] =$analysi['province_id'];
				$cord[] =$analysi['city_id'];
				$cord[] =$analysi['district_id'];
			}
			$realuser = $this->real_users_model->where(array('weixin_id'=>array('in',$openid)))->select();
			$region = $this->region_model->where(array('code'=>array('in',$cord)))->select();
		}
		$btypes = $this->arraytypes();
		$this->assign("region", $region);
		$this->assign("card_type", C('CARD_TYPE'));
		$this->assign("btypes", $btypes[1]);
		$this->assign("search", $btypes[0]);
		$this->assign("analysis", $analysis);
		$this->assign("realuser", $realuser);
		$this->assign("page", $page->show('Admin'));
		$this->assign("count",$count);
		$this->display();
	}
    function withdraw(){
		if(I('param.')){
            if(I('param.start_time')){
                    $search[] = array('time'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('time'=>array('elt',I('param.end_time')));
            }
            if(I('param.keyword')){
                    $search[] = array('openid'=>I('param.keyword'));
            }
			$_GET['keyword']=I('param.keyword');
            $_GET['start_time'] = I('param.start_time');
            $_GET['end_time'] = I('param.end_time');
		}

	        $count=$this->wxpayorder_model
	        ->where($search)
	        ->count();
	        $page = $this->page($count, 50);
	        $wxpayorder=$this->wxpayorder_model
	        ->where($search)
	        ->limit($page->firstRow . ',' . $page->listRows)
	        ->order("id DESC")
	        ->select();
			if($wxpayorder){
				foreach($wxpayorder as $wxpay){
					$openid[] =$wxpay['openid'];
				}
				$realuser = $this->real_users_model->where(array('weixin_id'=>array('in',$openid)))->select();
			}
			$btypes = $this->arraytypes();
	        $this->assign('wxpayorder',$wxpayorder);
	        $this->assign('wxpay_status', $btypes[2]);
	        $this->assign('wxpay_paytype', $btypes[3]);
	        $this->assign('realuser',$realuser);
	        $this->assign('page', $page->show('Admin'));
			$this->assign("count",$count);
	        $this->display();
	}
	//摇的记录
    function logs(){
    	if(I('param.time')){
			$time = array('date(datetime)'=>array('eq',I('param.time')));
			$_GET['time'] =I('param.time');
    	}
		$count=$this->analysis_logs_model
		->where($time)
		->count();
		$page = $this->page($count, 100);
		$analysis = $this->analysis_logs_model
		->where($time)
		->limit($page->firstRow . ',' . $page->listRows)
		->order("id DESC")
		->select();
		$this->assign("analysis", $analysis);
		$this->assign("page", $page->show('Admin'));
		$this->assign("count",$count);
		$this->display();
	}
	//链接记录
    function urls(){
    	if(I('param.time')){
			$time = array('date(datetime)'=>array('eq',I('param.time')));
			$_GET['time'] =I('param.time');
    	}
		$count=$this->analysis_urls_model
		->where($time)
		->count();
		$page = $this->page($count, 50);
		$analysis = $this->analysis_urls_model
		->where($time)
		->limit($page->firstRow . ',' . $page->listRows)
		->order("id DESC")
		->select();
		$this->assign("analysis", $analysis);
		$this->assign("page", $page->show('Admin'));
		$this->assign("count",$count);
		$this->display();
	}
	/**
     * 下载文件
     */
    public function download(){
        $backup_name = isset($_GET['backup']) && trim($_GET['backup']) ? trim($_GET['backup']) :
            $this->error('请选择文件名称！');
        $file = isset($_GET['file']) && trim($_GET['file']) ? trim($_GET['file']) : $this->
            error('请选择文件文件！');
        $sql_file = SITE_PATH . $this->backup_path . $backup_name . '/' . $file;
        if (file_exists($sql_file)){
            header('Content-type: application/unknown');
            header('Content-Disposition: attachment; filename="' . $file . '"');
            header("Content-Length: " . filesize($sql_file) . "; ");
            readfile($sql_file);
        }else{
            $this->error('文件不存在！');
        }
    }
	public function export_csv($filename, $data){
		$file_hwnd=fopen('data/runtime/'.$filename,"w");
		header("Content-type:text/csv");
		header("Content-Disposition:attachment;filename=".$filename);
		header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
		header('Expires:0');
		header('Pragma:public');
		fwrite($file_hwnd,$data);
		fclose($file_hwnd);
	}
    public function outdaycsv(){
		if(I('param.')){
            if(I('param.start_time')){
                    $search[] = array('date(datetime)'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('date(datetime)'=>array('elt',I('param.end_time')));
            }
            if(I('param.keyword')){
                    $search[] = array('pageid'=>I('param.keyword'));
            }
		}
		if(empty($search)){
			$search[] = array('date(datetime)'=>array('eq',date('Y-m-d',strtotime('-1 day'))));
		}
		$analysis = $this->analysis_day_model->where($search)->select();
		if(count($analysis) > 20000){
			$this->error('导出数据过多会导致内存溢出！请分别查询导出！');
		}
		$head[] = iconv('utf-8','GBK',",页面名称,时间,摇周边人数,摇周边次数,点击人数,点击次数,关联设备数,开启活动数,未开启活动数,参与人数,中奖次数,未中奖次数,红包次数,红包金额,卡券,实物\r\n");
		if($analysis){
			set_time_limit(0);
			foreach($analysis as$analy){
				$name = str_replace(array("\r\n", "\r", "\n",",","."), "", $analy['name']);
				$content[] = iconv('utf-8','GBK',"$name - ".$analy['pageid']).",".
						iconv('utf-8','GBK',$analy['datetime']).",".
						iconv('utf-8','GBK',$analy['shake_uv']).",".
						iconv('utf-8','GBK',$analy['shake_pv']).",".
						iconv('utf-8','GBK',$analy['click_uv']).",".
						iconv('utf-8','GBK',$analy['click_pv']).",".
						iconv('utf-8','GBK',$analy['count']).",".
						iconv('utf-8','GBK',$analy['open']).",".
						iconv('utf-8','GBK',$analy['close']).",".
						iconv('utf-8','GBK',$analy['partake']).",".
						iconv('utf-8','GBK',$analy['winning']).",".
						iconv('utf-8','GBK',$analy['nowinning']).",".
						iconv('utf-8','GBK',$analy['reds']).",".
						iconv('utf-8','GBK',$analy['moneys']).",".
						iconv('utf-8','GBK',$analy['cards']).",".
						iconv('utf-8','GBK',$analy['reals'])."\r\n";
			}
		}
		$csvname =time().'.csv';
		$str = implode(',',array_merge($head, $content));
		$this->export_csv($csvname,$str);
		$this->success('导出完成',U('Analysis/download', array('backup'=>'runtime', 'file'=>"$csvname")));
    }
    public function outactivitycsv(){
		if(I('param.')){
            if(I('param.start_time')){
                    $search[] = array('date(datetime)'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('date(datetime)'=>array('elt',I('param.end_time')));
            }
            if(I('param.keyword')){
                    $search[] = array('event_id'=>I('param.keyword'));
            }
		}
		if(empty($search)){
			$search[] = array('date(datetime)'=>array('eq',date('Y-m-d',strtotime('-1 day'))));
		}
		$analysis = $this->analysis_activity_model->where($search)->select();
		if(count($analysis) > 20000){
			$this->error('导出数据过多会导致内存溢出！请分别查询导出！');
		}
		$head[] = iconv('utf-8','GBK',",页面名称,时间,活动部署设备量,进入人数,进入次数,物料数量,中奖次数,未中奖次数\r\n");
		if($analysis){
			set_time_limit(0);
			foreach($analysis as$analy){
				$name = str_replace(array("\r\n", "\r", "\n",",","."), "", $analy['name']);
				$content[] = iconv('utf-8','GBK',"$name - ".$analy['event_id']).",".
						iconv('utf-8','GBK',$analy['datetime']).",".
						iconv('utf-8','GBK',$analy['device']).",".
						iconv('utf-8','GBK',$analy['enter_uv']).",".
						iconv('utf-8','GBK',$analy['enter_pv']).",".
						iconv('utf-8','GBK',$analy['materials']).",".
						iconv('utf-8','GBK',$analy['winning']).",".
						iconv('utf-8','GBK',$analy['nowinning']).","."\r\n";
			}
		}
		$csvname =time().'.csv';
		$str = implode(',',array_merge($head, $content));
		$this->export_csv($csvname,$str);
		$this->success('导出完成',U('Analysis/download', array('backup'=>'runtime', 'file'=>"$csvname")));
    }
    public function outmaterialscsv(){
		if(I('param.')){
            if(I('param.start_time')){
                    $search[] = array('date(datetime)'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('date(datetime)'=>array('elt',I('param.end_time')));
            }
            if(I('param.keyword')){
                    $search[] = array('card_id'=>I('param.keyword'));
            }
		}
		if(empty($search)){
			$search[] = array('date(datetime)'=>array('eq',date('Y-m-d',strtotime('-1 day'))));
		}
		$analysis = $this->analysis_materials_model->where($search)->select();
		if(count($analysis) > 20000){
			$this->error('导出数据过多会导致内存溢出！请分别查询导出！');
		}
		$card_type = C('CARD_TYPE');
		$head[] = iconv('utf-8','GBK',",物料名称,时间,物料类型,展示人数,展示次数,中奖次数,未中奖次数,红包金额/卡券数量\r\n");
		if($analysis){
			set_time_limit(0);
			foreach($analysis as$analy){
				if($analy['card_type'] == 1){
        			$money = $analy['moneys']/100 .'元';
        		}
        		if($analy['card_type'] != 1){
        			$money = $analy['moneys'].'个';
        		}
				$name = str_replace(array("\r\n", "\r", "\n",",","."), "", $analy['name']);
				$content[] = iconv('utf-8','GBK',"$name - ".$analy['card_id']).",".
						iconv('utf-8','GBK',$analy['datetime']).",".
						iconv('utf-8','GBK',$card_type[$analy['card_type']-1]['name']).",".
						iconv('utf-8','GBK',$analy['display_uv']).",".
						iconv('utf-8','GBK',$analy['display_pv']).",".
						iconv('utf-8','GBK',$analy['winning']).",".
						iconv('utf-8','GBK',$analy['nowinning']).",".
						iconv('utf-8','GBK',$money).","."\r\n";
			}
		}
		$csvname =time().'.csv';
		$str = implode(',',array_merge($head, $content));
		$this->export_csv($csvname,$str);
		$this->success('导出完成',U('Analysis/download', array('backup'=>'runtime', 'file'=>"$csvname")));
    }
    public function outequipmentcsv(){
		if(I('param.')){
			$keyword =I('param.keyword');
			if(I('param.search') ==1){$search[] = array('devid'=>array('like',"%$keyword%"));}
			if(I('param.search') ==2){$search[] = array('bsname'=>array('like',"%$keyword%"));}
			if(I('param.search') ==3){$search[] = array('bsaddress'=>array('like',"%$keyword%"));}
			if(I('param.search') ==4){$search[] = array('partner'=>array('like',"%$keyword%"));}
			if(I('param.search') ==5){$search[] = array('mobile'=>array('like',"%$keyword%"));}
			if(I('param.search') ==6){
				$sregion = "name like'%$keyword%' or name_en like'%$keyword%'";
				$region = $this->region_model->where("$sregion")->find();
				$search[] =array(array('province_id'=>$region['code']),
								'_logic'=>"OR",
								array('city_id'=>$region['code']),
								'_logic'=>"OR",
								array('district_id'=>$region['code']),
								);
			}
            if(I('param.bstype')){
                $search[] = array('bstype'=>I('param.bstype'));
            }
            if(I('param.start_time')){
                    $search[] = array('date(datetime)'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('date(datetime)'=>array('elt',I('param.end_time')));
            }
		}
		if(empty($search)){
			$search[] = array('date(datetime)'=>array('eq',date('Y-m-d',strtotime('-1 day'))));
		}

		$search[]= array('click_uv'=>array('egt',1),"bsname != '未绑定店铺信息'");
		$analysis = $this->analysis_equipment_model->where($search)->select();
		if(count($analysis) > 20000){
			$this->error('导出数据过多会导致内存溢出！请分别查询导出！');
		}
		$card_type = C('CARD_TYPE');
		$head[] = iconv('utf-8','GBK',",时间,设备ID,省,市,区,合伙人,店铺名称,店铺类型,摇一摇人数,摇一摇次数,活动数,中奖次数,未中奖次数,红包数,红包金额,卡券数,实物数,店铺地址,电话\r\n");
		if($analysis){
			set_time_limit(0);
			$region = $this->region_model->select();
			$btypes = $this->arraytypes();
			foreach($analysis as$analy){
//				\Think\Log::record('equipment:'.json_encode($analy));

				foreach($btypes[1] as$bts){
					if($bts['id'] == $analy['bstype']){
						$bstname = $bts['name'];
					}
				}
				foreach($region as$rg){
					if($rg['code'] == $analy['province_id']){
						$pname = $rg['name'];
					}
					if($rg['code'] == $analy['city_id']){
						$cname = $rg['name'];
					}
					if($rg['code'] == $analy['district_id']){
						$dname = $rg['name'];
					}
				}
				if(!$pname && !$cname && !$dname){
					$pname = '中国';
					$cname = $dname = '';
				}
				$partner = str_replace(array("\r\n", "\r", "\n",",","."), "", $analy['partner']);
				$bsname = str_replace(array("\r\n", "\r", "\n",",","."), "", $analy['bsname']);
				$bsaddress = str_replace(array("\r\n", "\r", "\n",",","."), "", $analy['bsaddress']);
				$content[] = iconv('utf-8','GBK',$analy['datetime']).",".
						iconv('utf-8','GBK',$analy['devid']).",".
						iconv('utf-8','GBK',$pname).",".
						iconv('utf-8','GBK',$cname).",".
						iconv('utf-8','GBK',$dname).",".
						iconv('utf-8','GBK',$partner).",".
						iconv('utf-8','GBK',$bsname).",".
						iconv('utf-8','GBK',$bstname).",".
						iconv('utf-8','GBK',$analy['click_uv']).",".
						iconv('utf-8','GBK',$analy['click_pv']).",".
						iconv('utf-8','GBK',$analy['activitys']).",".
						iconv('utf-8','GBK',$analy['winning']).",".
						iconv('utf-8','GBK',$analy['nowinning']).",".
						iconv('utf-8','GBK',$analy['reds']).",".
						iconv('utf-8','GBK',$analy['moneys']).",".
						iconv('utf-8','GBK',$analy['cards']).",".
						iconv('utf-8','GBK',$analy['reals']).",".
						iconv('utf-8','GBK',$bsaddress).",".
						iconv('utf-8','GBK',$analy['mobile']).","."\r\n";
			}
		}
		$csvname =time().'.csv';
		$str = implode(',',array_merge($head, $content));
		$this->export_csv($csvname,$str);
		$this->success('导出完成',U('Analysis/download', array('backup'=>'runtime', 'file'=>"$csvname")));
    }
    public function outuserscsv(){
		if(I('param.')){
            if(I('param.keyword')){
                    $search[] = array('openid'=>I('param.keyword'));
            }
            if(I('param.btime')){
	            if(I('param.btime') == 1){
		            if(I('param.start_time')){
		                    $search[] = array('date(datetime)'=>array('egt',I('param.start_time')));
		            }
		            if(I('param.end_time')){
		                    $search[] = array('date(datetime)'=>array('elt',I('param.end_time')));
		            }
	            }
	            if(I('param.btime') == 2){
		            if(I('param.start_time')){
		                    $search[] = array('date(registered)'=>array('egt',I('param.start_time')));
		            }
		            if(I('param.end_time')){
		                    $search[] = array('date(registered)'=>array('elt',I('param.end_time')));
		            }
	            }
	            if(I('param.btime') == 3){
		            if(I('param.start_time')){
		                    $search[] = array('date(enter)'=>array('egt',I('param.start_time')));
		            }
		            if(I('param.end_time')){
		                    $search[] = array('date(enter)'=>array('elt',I('param.end_time')));
		            }
	            }
            }
		}
		if(empty($search)){
			$search[] = array('date(datetime)'=>array('eq',date('Y-m-d',strtotime('-1 day'))));
		}
		$analysis = $this->analysis_users_model->where($search)->select();
		if(count($analysis) > 20000){
			$this->error('导出数据过多会导致内存溢出！请分别查询导出！');
		}
		$head[] = iconv('utf-8','GBK',",时间,openid,用户昵称,注册日期,最后登录时间,中奖数,红包数,红包金额,卡券数,物料数,摇的次数\r\n");
		if($analysis){
			set_time_limit(0);
			foreach($analysis as$analy){
				$nickname = str_replace(array("\r\n", "\r", "\n",",","."), "", $analy['nickname']);
				$content[] = iconv('utf-8','GBK',$analy['datetime']).",".
						iconv('utf-8','GBK',$analy['openid']).",".
						iconv('utf-8','GBK',$nickname).",".
						iconv('utf-8','GBK',$analy['registered']).",".
						iconv('utf-8','GBK',$analy['enter']).",".
						iconv('utf-8','GBK',$analy['winning']).",".
						iconv('utf-8','GBK',$analy['reds']).",".
						iconv('utf-8','GBK',$analy['moneys']).",".
						iconv('utf-8','GBK',$analy['cards']).",".
						iconv('utf-8','GBK',$analy['reals']).",".
						iconv('utf-8','GBK',$analy['shakes']).","."\r\n";
			}
		}
		$csvname =time().'.csv';
		$str = implode(',',array_merge($head, $content));
		$this->export_csv($csvname,$str);
		$this->success('导出完成',U('Analysis/download', array('backup'=>'runtime', 'file'=>"$csvname")));
    }

    public function outwinningcsv(){
		if(I('param.')){
			$keyword =I('param.keyword');
			if(I('param.search') ==1){$search[] = array('devid'=>array('like',"%$keyword%"));}
			if(I('param.search') ==2){$search[] = array('bsname'=>array('like',"%$keyword%"));}
			if(I('param.search') ==3){$search[] = array('bsaddress'=>array('like',"%$keyword%"));}
			if(I('param.search') ==4){$search[] = array('partner'=>array('like',"%$keyword%"));}
			if(I('param.search') ==5){$search[] = array('mobile'=>array('like',"%$keyword%"));}
			if(I('param.search') ==6){
				$sregion = "name like'%$keyword%' or name_en like'%$keyword%'";
				$region = $this->region_model->where("$sregion")->find();
				$search[] =array(array('province_id'=>$region['code']),
								'_logic'=>"OR",
								array('city_id'=>$region['code']),
								'_logic'=>"OR",
								array('district_id'=>$region['code']),
								);
			}
            if(I('param.bstype')){
                $search[] = array('bstype'=>I('param.bstype'));
            }
            if(I('param.bctype')){
                $search[] = array('ctype'=>I('param.bctype'));
            }
            if(I('param.start_time')){
                    $search[] = array('datetime'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('datetime'=>array('elt',I('param.end_time')));
            }
		}
		if(empty($search)){
			$search[] = array('datetime'=>array('egt',date('Y-m-d 00:00:00',strtotime('-1 day'))));
		}
		$analysis = $this->analysis_winning_model->where($search)->select();
		if(count($analysis) > 20000){
			$this->error('导出数据过多会导致内存溢出！请分别查询导出！');
		}
		$card_type = C('CARD_TYPE');
		$head[] = iconv('utf-8','GBK',",摇的时间,设备ID,店铺名称,店铺类型,店铺地址,店铺地区,合伙人,电话,用户ID,用户昵称,用户姓名,用户电话,用户地址,活动ID,活动类型,活动名称,物料ID,物料类型,物料名称,中奖金额,卡券编号,流水号\r\n");
		if($analysis){
			set_time_limit(0);
			$region = $this->region_model->select();
			$btypes = $this->arraytypes();
			$card_type = C('CARD_TYPE');
			foreach($analysis as$analy){
				foreach($btypes[1] as$bts){
					if($bts['id'] == $analy['bstype']){
						$bstname = $bts['name'];
					}
				}
				foreach($region as$rg){
					if($rg['code'] == $analy['province_id']){
						$pname = $rg['name'];
					}
					if($rg['code'] == $analy['city_id']){
						$cname = $rg['name'];
					}
					if($rg['code'] == $analy['district_id']){
						$dname = $rg['name'];
					}
				}
				if($pname && $cname && $dname){
					$reg = $pname.' - '.$cname.' - '.$dname;
				}else{
					$reg = '中国';
				}
				if($analy['etype'] == 1 ){ $etype = '摇一摇';}else{ $etype = '扫一扫';}
				$realuser = $this->real_users_model->where(array('weixin_id'=>$analy['openid']))->find();
				$bsname = str_replace(array("\r\n", "\r", "\n",",","."), "", $analy['bsname']);
				$bsaddress = str_replace(array("\r\n", "\r", "\n",",","."), "", $analy['bsaddress']);
				$partner = str_replace(array("\r\n", "\r", "\n",",","."), "", $analy['partner']);
				$nickname = str_replace(array("\r\n", "\r", "\n",",","."), "", $realuser['nickname']);
				$realname = str_replace(array("\r\n", "\r", "\n",",","."), "", $realuser['realname']);
				$phone = str_replace(array("\r\n", "\r", "\n",",","."), "", $realuser['phone']);
				$uaddress = str_replace(array("\r\n", "\r", "\n",",","."), "", $realuser['address']);
				$content[] = iconv('utf-8','GBK',$analy['datetime']).",".
						iconv('utf-8','GBK',$analy['devid']).",".
						iconv('utf-8','GBK',$bsname).",".
						iconv('utf-8','GBK',$bstname).",".
						iconv('utf-8','GBK',$bsaddress).",".
						iconv('utf-8','GBK',$reg).",".
						iconv('utf-8','GBK',$partner).",".
						iconv('utf-8','GBK',$analy['mobile']).",".
						iconv('utf-8','GBK',$analy['openid']).",".
						iconv('utf-8','GBK',$nickname).",".
						iconv('utf-8','GBK',$uaddress).",".
						iconv('utf-8','GBK',$uaddress).",".
						iconv('utf-8','GBK',$uaddress).",".
						iconv('utf-8','GBK',$analy['eid']).",".
						iconv('utf-8','GBK',$etype).",".
						iconv('utf-8','GBK',$analy['ename']).",".
						iconv('utf-8','GBK',$analy['cid']).",".
						iconv('utf-8','GBK',$card_type[$analy['ctype']-1]['name']).",".
						iconv('utf-8','GBK',$analy['cname']).",".
						iconv('utf-8','GBK',$analy['moneys']).",".
						iconv('utf-8','GBK',$analy['cardnum']).",".
						iconv('utf-8','GBK',$analy['sn']).","."\r\n";
			}
		}
		$csvname =time().'.csv';
		$str = implode(',',array_merge($head, $content));
		$this->export_csv($csvname,$str);
		$this->success('导出完成',U('Analysis/download', array('backup'=>'runtime', 'file'=>"$csvname")));
    }

    public function outwithdrawcsv(){
		if(I('param.')){
            if(I('param.start_time')){
                    $search[] = array('time'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('time'=>array('elt',I('param.end_time')));
            }
            if(I('param.keyword')){
                    $search[] = array('openid'=>I('param.keyword'));
            }
		}
		if(empty($search)){
			$search[] = array('time'=>array('egt',date('Y-m-d 00:00:00',strtotime('-1 day'))));
		}
		$analysis = $this->wxpayorder_model
			->field("`openid`,sum(`total_amount`) as `moneys`")
	        ->where($search)
	        ->group('openid')
	        ->select();
		if(count($analysis) > 20000){
			$this->error('导出数据过多会导致内存溢出！请分别查询导出！');
		}
		$head[] = iconv('utf-8','GBK',",openid,用户昵称,注册日期,累计金额(元)\r\n");
		if($analysis){
			set_time_limit(0);
			foreach($analysis as$analy){
				$realuser = $this->real_users_model->where(array('weixin_id'=>$analy['openid']))->find();

				$nickname = str_replace(array("\r\n", "\r", "\n",",","."), "", $realuser['nickname']);
				$content[] = iconv('utf-8','GBK',$analy['openid']).",".
						iconv('utf-8','GBK',$nickname).",".
						iconv('utf-8','GBK',$realuser['created_at']).",".
						iconv('utf-8','GBK',$analy['moneys']/100).","."\r\n";
			}
		}
		$csvname =time().'.csv';
		$str = implode(',',array_merge($head, $content));
		$this->export_csv($csvname,$str);
		$this->success('导出完成',U('Analysis/download', array('backup'=>'runtime', 'file'=>"$csvname")));
    }
}
